import { defineStore } from 'pinia';
import { Settings } from '../../types';
import StorageManager from '../../utils/storage';
import CryptoManager from '../../utils/crypto';

interface SettingsState {
  settings: Settings;
  loading: boolean;
  error: string | null;
  storageInfo: {
    currentSize: number;
    limitSize: number;
  };
}

export const useSettingsStore = defineStore('settings', {
  state: (): SettingsState => ({
    settings: {
      id: '1',
      autoBackup: true,
      backupFrequency: 7,
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString()
    },
    loading: false,
    error: null,
    storageInfo: {
      currentSize: 0,
      limitSize: 0
    }
  }),

  getters: {
    // 获取设置
    getSettings: (state) => state.settings,
    
    // 获取是否启用自动备份
    isAutoBackupEnabled: (state) => state.settings.autoBackup,
    
    // 获取备份频率
    getBackupFrequency: (state) => state.settings.backupFrequency,
    
    // 获取最后备份时间
    getLastBackupTime: (state) => state.settings.lastBackupTime,
    
    // 获取存储信息
    getStorageInfo: (state) => state.storageInfo
  },

  actions: {
    // 加载设置
    async loadSettings() {
      this.loading = true;
      this.error = null;
      try {
        this.settings = await StorageManager.getSettings();
        await this.updateStorageInfo();
      } catch (error) {
        this.error = '加载设置失败';
        console.error('加载设置失败:', error);
      } finally {
        this.loading = false;
      }
    },

    // 更新存储信息
    async updateStorageInfo() {
      try {
        const storageInfo = await StorageManager.getStorageInfo();
        this.storageInfo = {
          currentSize: storageInfo.currentSize,
          limitSize: storageInfo.limitSize
        };
      } catch (error) {
        console.error('获取存储信息失败:', error);
      }
    },

    // 更新设置
    async updateSettings(settings: Partial<Settings>) {
      this.loading = true;
      this.error = null;
      try {
        const updatedSettings = {
          ...this.settings,
          ...settings,
          updateTime: new Date().toISOString()
        };
        await StorageManager.saveSettings(updatedSettings);
        this.settings = updatedSettings;
        await this.updateStorageInfo();
      } catch (error) {
        this.error = '更新设置失败';
        console.error('更新设置失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 设置访问密码
    async setPassword(password: string) {
      this.loading = true;
      this.error = null;
      try {
        if (!CryptoManager.validatePassword(password)) {
          throw new Error('密码强度不足');
        }
        await this.updateSettings({ password });
      } catch (error) {
        this.error = '设置密码失败';
        console.error('设置密码失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 验证访问密码
    async validatePassword(password: string): Promise<boolean> {
      return this.settings.password === password;
    },

    // 启用/禁用自动备份
    async toggleAutoBackup(enabled: boolean) {
      await this.updateSettings({ autoBackup: enabled });
    },

    // 设置备份频率
    async setBackupFrequency(frequency: number) {
      if (frequency < 1) {
        throw new Error('备份频率必须大于0');
      }
      await this.updateSettings({ backupFrequency: frequency });
    },

    // 更新最后备份时间
    async updateLastBackupTime() {
      await this.updateSettings({
        lastBackupTime: new Date().toISOString()
      });
    },

    // 备份数据
    async backupData() {
      this.loading = true;
      this.error = null;
      
      try {
        // 获取所有数据
        const allData = await StorageManager.getAllData();
        
        // 数据序列化
        const dataString = JSON.stringify(allData);
        
        // 创建文件名
        const fileName = `favorflow_backup_${new Date().getTime()}.json`;
        
        // #ifdef MP-WEIXIN
        try {
          // 微信小程序环境
          // 保存数据到临时文件
          const fs = uni.getFileSystemManager();
          const tempFilePath = `${wx.env.USER_DATA_PATH}/${fileName}`;
          
          await new Promise<void>((resolve, reject) => {
            fs.writeFile({
              filePath: tempFilePath,
              data: dataString,
              encoding: 'utf8',
              success: () => {
                console.log('【备份】数据已写入临时文件', tempFilePath);
                resolve();
              },
              fail: (err) => {
                console.error('【备份】写入临时文件失败', err);
                reject(new Error('写入临时文件失败'));
              }
            });
          });
          
          // 验证文件是否已创建
          try {
            fs.accessSync(tempFilePath);
            console.log('【备份】文件已创建，确认存在');
          } catch (err) {
            console.error('【备份】验证文件失败:', err);
            throw new Error('无法访问备份文件，请重试');
          }
          
          // 保存全局变量，供按钮点击时使用
          const app = getApp();
          if (app) {
            app.globalData = app.globalData || {};
            app.globalData.backupFilePath = tempFilePath;
            app.globalData.pendingBackup = true;
          }
          
          // 显示操作引导弹窗
          uni.showModal({
            title: '备份文件已准备好',
            content: '请点击确定按钮，然后在弹出的分享面板中选择"发送给朋友"或"保存到手机"。',
            confirmText: '立即分享',
            success: (res) => {
              if (res.confirm) {
                // 创建按钮并模拟点击事件
                uni.navigateTo({
                  url: '/pages/share/share-file?path=' + encodeURIComponent(tempFilePath) + '&name=' + encodeURIComponent(fileName),
                  success: () => {
                    console.log('【备份】跳转到分享页面成功');
                  },
                  fail: (err) => {
                    console.error('【备份】跳转到分享页面失败', err);
                    // 如果跳转失败，尝试直接调用分享API
                    try {
                      // @ts-ignore
                      if (wx && typeof wx.shareFileMessage === 'function') {
                        // @ts-ignore
                        wx.shareFileMessage({
                          filePath: tempFilePath,
                          success: () => {
                            console.log('【备份】直接分享成功');
                            this.updateLastBackupTime();
                          },
                          fail: (shareErr) => {
                            console.error('【备份】直接分享失败', shareErr);
                            uni.showToast({
                              title: '分享失败，请重试',
                              icon: 'none'
                            });
                          }
                        });
                      } else {
                        uni.showToast({
                          title: '分享失败，请重试',
                          icon: 'none'
                        });
                      }
                    } catch (shareError) {
                      console.error('【备份】调用分享API失败', shareError);
                      uni.showToast({
                        title: '分享失败，请重试',
                        icon: 'none'
                      });
                    }
                  }
                });
              }
            }
          });
          
          // 设置页面返回监听，检查备份是否成功
          const checkBackupStatusOnReturn = () => {
            const app = getApp();
            let backupSuccess = false;
            
            // 首先检查全局变量
            if (app && app.globalData) {
              backupSuccess = !!app.globalData.backupSuccess;
              if (backupSuccess) {
                app.globalData.backupSuccess = false;
                app.globalData.pendingBackup = false;
              }
            }
            
            // 如果全局变量中没有成功标记，再检查本地存储
            if (!backupSuccess) {
              try {
                const storedSuccess = uni.getStorageSync('backup_success');
                if (storedSuccess === 'true') {
                  backupSuccess = true;
                  // 清除标记
                  uni.removeStorageSync('backup_success');
                  
                  // 使用存储的时间戳更新备份时间
                  const timestamp = uni.getStorageSync('backup_timestamp');
                  if (timestamp) {
                    this.updateSettings({
                      lastBackupTime: timestamp
                    });
                    uni.removeStorageSync('backup_timestamp');
                  } else {
                    this.updateLastBackupTime();
                  }
                }
              } catch (e) {
                console.error('读取备份状态失败:', e);
              }
            } else {
              // 使用全局变量方式更新备份时间
              this.updateLastBackupTime();
            }
            
            if (backupSuccess) {
              console.log('【备份】分享成功，已更新备份时间');
            } else if (app && app.globalData && app.globalData.pendingBackup) {
              // 用户没有完成分享
              app.globalData.pendingBackup = false;
              console.log('【备份】用户未完成分享流程');
            }
          };
          
          // 监听页面显示事件以检查状态
          const pages = getCurrentPages();
          const currentPage = pages[pages.length - 1];
          if (currentPage && currentPage.$vm) {
            const originalOnShow = currentPage.$vm.$options.onShow;
            currentPage.$vm.$options.onShow = function() {
              if (originalOnShow) {
                originalOnShow.call(this);
              }
              checkBackupStatusOnReturn();
            };
          }
        } catch (error) {
          console.error('【备份】微信小程序备份失败', error);
          throw error;
        }
        // #endif
        
        // #ifdef H5
        try {
          // H5环境
          const blob = new Blob([dataString], { type: 'application/json' });
          const url = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = fileName;
          a.click();
          URL.revokeObjectURL(url);
          console.log('【备份】H5备份完成');
        } catch (error) {
          console.error('【备份】H5备份失败', error);
          throw error;
        }
        // #endif
        
        // #ifdef APP-PLUS
        try {
          // App环境
          const dirPath = plus.io.convertLocalFileSystemURL('_doc');
          const filePath = `${dirPath}/${fileName}`;
          
          const fileEntry = await new Promise<any>((resolve, reject) => {
            plus.io.resolveLocalFileSystemURL('_doc', (entry) => {
              entry.getFile(fileName, { create: true, exclusive: false }, (fileEntry) => {
                resolve(fileEntry);
              }, (error) => {
                reject(error);
              });
            }, (error) => {
              reject(error);
            });
          });
          
          await new Promise<void>((resolve, reject) => {
            fileEntry.createWriter((writer) => {
              writer.onwrite = () => {
                resolve();
              };
              writer.onerror = (error) => {
                reject(error);
              };
              writer.write(dataString);
            }, (error) => {
              reject(error);
            });
          });
          
          uni.showModal({
            title: '备份成功',
            content: `备份文件已保存到: ${filePath}`,
            showCancel: false
          });
          
          console.log('【备份】App备份完成');
        } catch (error) {
          console.error('【备份】App备份失败', error);
          throw error;
        }
        // #endif
        
        // 更新最后备份时间
        await this.updateLastBackupTime();
        
        console.log('【备份】备份完成');
      } catch (error) {
        this.error = '备份数据失败';
        console.error('【备份】备份数据失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    // 恢复数据
    async restoreData() {
      this.loading = true;
      this.error = null;
      
      try {
        let fileContent = '';
        
        // #ifdef MP-WEIXIN
        try {
          // 微信小程序环境
          const res = await new Promise<UniApp.ChooseMessageFileSuccessCallbackResult>((resolve, reject) => {
            uni.chooseMessageFile({
              count: 1,
              type: 'file',
              extension: ['.json'],
              success: (res) => resolve(res),
              fail: (err) => reject(err)
            });
          });
          
          if (!res.tempFiles || res.tempFiles.length === 0) {
            throw new Error('未选择文件');
          }
          
          const filePath = res.tempFiles[0].path;
          
          fileContent = await new Promise<string>((resolve, reject) => {
            const fs = uni.getFileSystemManager();
            fs.readFile({
              filePath,
              encoding: 'utf8',
              success: (res) => resolve(res.data as string),
              fail: (err) => reject(err)
            });
          });
        } catch (error) {
          console.error('【恢复】微信小程序选择文件失败', error);
          throw error;
        }
        // #endif
        
        // #ifdef H5
        try {
          // H5环境
          const input = document.createElement('input');
          input.type = 'file';
          input.accept = '.json';
          
          const file = await new Promise<File>((resolve, reject) => {
            input.onchange = (e) => {
              const files = (e.target as HTMLInputElement).files;
              if (files && files.length > 0) {
                resolve(files[0]);
              } else {
                reject(new Error('未选择文件'));
              }
            };
            input.click();
          });
          
          fileContent = await new Promise<string>((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = (e) => {
              resolve(e.target?.result as string);
            };
            reader.onerror = () => {
              reject(new Error('读取文件失败'));
            };
            reader.readAsText(file);
          });
        } catch (error) {
          console.error('【恢复】H5选择文件失败', error);
          throw error;
        }
        // #endif
        
        // #ifdef APP-PLUS
        try {
          // App环境
          const filePath = await new Promise<string>((resolve, reject) => {
            plus.io.resolveLocalFileSystemURL('_doc', (entry) => {
              entry.createReader().readEntries((entries) => {
                // 过滤出备份文件
                const backupFiles = entries.filter((file: any) => 
                  file.isFile && 
                  file.name.startsWith('favorflow_backup_') && 
                  file.name.endsWith('.json')
                );
                
                if (backupFiles.length === 0) {
                  reject(new Error('未找到备份文件'));
                  return;
                }
                
                // 显示文件列表让用户选择
                const fileList = backupFiles.map((file: any) => {
                  const timestamp = file.name.split('_')[2].split('.')[0];
                  const date = new Date(parseInt(timestamp));
                  return {
                    name: file.name,
                    date: date.toLocaleString(),
                    path: file.fullPath
                  };
                });
                
                // 按时间排序，最新的在前面
                fileList.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
                
                const items = fileList.map(item => ({
                  title: `备份于 ${item.date}`,
                  path: item.path
                }));
                
                uni.showActionSheet({
                  itemList: items.map(item => item.title),
                  success: (res) => {
                    resolve(items[res.tapIndex].path);
                  },
                  fail: () => {
                    reject(new Error('用户取消选择'));
                  }
                });
              });
            }, (error) => {
              reject(error);
            });
          });
          
          fileContent = await new Promise<string>((resolve, reject) => {
            plus.io.resolveLocalFileSystemURL(filePath, (entry) => {
              entry.file((file) => {
                const reader = new plus.io.FileReader();
                reader.onloadend = (e) => {
                  resolve(reader.result);
                };
                reader.onerror = (e) => {
                  reject(new Error('读取文件失败'));
                };
                reader.readAsText(file);
              });
            }, (error) => {
              reject(error);
            });
          });
        } catch (error) {
          console.error('【恢复】App选择文件失败', error);
          throw error;
        }
        // #endif
        
        if (!fileContent) {
          throw new Error('未获取到文件内容');
        }
        
        // 解析数据
        const parsedData = JSON.parse(fileContent);
        
        // 验证数据结构
        if (!parsedData.contacts || !Array.isArray(parsedData.contacts) ||
            !parsedData.records || !Array.isArray(parsedData.records) ||
            !parsedData.categories || !Array.isArray(parsedData.categories) ||
            !parsedData.settings) {
          throw new Error('备份文件格式不正确');
        }
        
        // 恢复数据
        await StorageManager.saveAllData(parsedData);
        
        // 重新加载设置
        await this.loadSettings();
        
        console.log('【恢复】数据恢复完成');
      } catch (error) {
        this.error = '恢复数据失败';
        console.error('【恢复】恢复数据失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 重置设置
    async resetSettings() {
      this.loading = true;
      this.error = null;
      try {
        const defaultSettings: Settings = {
          id: '1',
          autoBackup: true,
          backupFrequency: 7,
          createTime: new Date().toISOString(),
          updateTime: new Date().toISOString()
        };
        await StorageManager.saveSettings(defaultSettings);
        this.settings = defaultSettings;
        await this.updateStorageInfo();
      } catch (error) {
        this.error = '重置设置失败';
        console.error('重置设置失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    }
  },

  persist: true
}); 